package top.wshape1.shiziapi.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.wshape1.shiziapi.common.domain.to.ProjectUserIdTo;
import top.wshape1.shiziapi.common.domain.vo.MessageVo;
import top.wshape1.shiziapi.message.constant.MsgConstant;
import top.wshape1.shiziapi.message.domain.MessageUser;
import top.wshape1.shiziapi.message.mapper.MessageUserMapper;
import top.wshape1.shiziapi.message.service.MessageUserService;
import top.wshape1.shiziapi.message.service.WebSocketService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Wshape1
 * @description 针对表【t_message_user】的数据库操作Service实现
 * @since 2023-09-18 22:09:06
 */
@Service
public class MessageUserServiceImpl extends ServiceImpl<MessageUserMapper, MessageUser>
        implements MessageUserService {

    @Value("${shiziapi.message.template.invite-msg-title}")
    private String inviteMsgTitle;

    @Value("${shiziapi.message.template.invite-msg-content}")
    private String inviteMsgContent;

    @Value("${shiziapi.message.template.reject-msg-title}")
    private String rejectMsgTitle;

    @Value("${shiziapi.message.template.reject-msg-content}")
    private String rejectMsgContent;

    @Resource
    private WebSocketService webSocketService;

    @Override
    public void read(Long msgId, Long userId) {

        MessageUser msg = this.getById(msgId);

        if (msg != null && Objects.equals(msg.getUserId(), userId)) {

            if (msg.getIsRead() != MsgConstant.READ) {
                update(new LambdaUpdateWrapper<MessageUser>()
                        .eq(MessageUser::getId, msgId)
                        .set(MessageUser::getIsRead, MsgConstant.READ)
                        .set(MessageUser::getReadTime, new Date())
                );
            }

        }

    }

    @Override
    public long countUnread(Long userId) {
        return count(new LambdaQueryWrapper<MessageUser>()
                .eq(MessageUser::getUserId, userId)
                .eq(MessageUser::getIsRead, MsgConstant.UNREAD)
        );
    }

    @Override
    public List<MessageVo> getPrivateMsg(Long userId) {

        List<MessageUser> list = list(new LambdaQueryWrapper<MessageUser>()
                .eq(MessageUser::getUserId, userId)
                .eq(MessageUser::getType, MsgConstant.NORMAL_MSG)
                .orderByAsc(MessageUser::getIsRead)
                .orderByDesc(MessageUser::getCreateTime)
        );

        return list.stream().map(msg -> {
            MessageVo messageVo = new MessageVo();
            BeanUtils.copyProperties(msg, messageVo);
            messageVo.setBroadcast(false);
            messageVo.setRead(msg.getIsRead() == MsgConstant.READ);
            return messageVo;
        }).toList();
    }

    @Override
    public List<MessageVo> getInviteMsg(Long userId) {
        List<MessageUser> list = list(new LambdaQueryWrapper<MessageUser>()
                .eq(MessageUser::getUserId, userId)
                .eq(MessageUser::getType, MsgConstant.INVITE_MSG)
                .orderByAsc(MessageUser::getIsRead)
                .orderByDesc(MessageUser::getCreateTime)
        );

        return list.stream().map(msg -> {
            MessageVo messageVo = new MessageVo();
            BeanUtils.copyProperties(msg, messageVo);
            messageVo.setBroadcast(false);
            messageVo.setRead(msg.getIsRead() == MsgConstant.READ);
            return messageVo;
        }).toList();
    }

    @Override
    public void sendInviteMsg(Long projectId, String projectName, Long userId, String userName, Long memberId) {

        MessageUser messageUser = new MessageUser();
        // 设置接收方的用户ID
        messageUser.setUserId(memberId);
        Date date = new Date();
        messageUser.setSendTime(date);
        messageUser.setCreateTime(date);
        messageUser.setIsRead(MsgConstant.UNREAD);
        messageUser.setType(MsgConstant.INVITE_MSG);

        messageUser.setTitle(renderMsgTemplate(inviteMsgTitle, projectId, projectName, userId, userName));
        messageUser.setContent(renderMsgTemplate(inviteMsgContent, projectId, projectName, userId, userName));

        // 保存到数据库
        this.save(messageUser);

        // 发送实时消息（如果在线）
        MessageVo messageVo = new MessageVo();
        BeanUtils.copyProperties(messageUser, messageVo);
        messageVo.setBroadcast(false);
        webSocketService.sendMessage(memberId, messageVo);

    }

    @Override
    public ProjectUserIdTo getAndParseId(Long msgId) {
        MessageUser messageUser = getById(msgId);

        if (messageUser != null) {
            String title = messageUser.getTitle();
            String content = messageUser.getContent();

            long projectId = Long.parseLong(title.split("\\(")[1].split("\\)")[0]);
            long userId = Long.parseLong(content.split("\\(")[1].split("\\)")[0]);

            return new ProjectUserIdTo(projectId, userId);
        }

        return null;
    }

    @Override
    public void sendRejectMsg(Long projectId, String projectName, Long memberId, String memberName, Long userId) {
        MessageUser messageUser = new MessageUser();
        // 设置接收方的用户ID
        messageUser.setUserId(userId);
        Date date = new Date();
        messageUser.setSendTime(date);
        messageUser.setCreateTime(date);
        messageUser.setIsRead(MsgConstant.UNREAD);
        messageUser.setType(MsgConstant.NORMAL_MSG);

        messageUser.setTitle(renderMsgTemplate(rejectMsgTitle, projectId, projectName, memberId, memberName));
        messageUser.setContent(renderMsgTemplate(rejectMsgContent, projectId, projectName, memberId, memberName));

        // 保存到数据库
        this.save(messageUser);

        // 发送实时消息（如果在线）
        MessageVo messageVo = new MessageVo();
        BeanUtils.copyProperties(messageUser, messageVo);
        messageVo.setBroadcast(false);
        webSocketService.sendMessage(userId, messageVo);
    }


    private String renderMsgTemplate(String template, Long projectId, String projectName, Long userId, String userName) {
        return template
                .replace("{projectId}", projectId.toString())
                .replace("{projectName}", projectName)
                .replace("{userId}", userId.toString())
                .replace("{userName}", userName)
                .replace("{time}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                ;
    }

}




